<template>
  <div>
    <!-- 顶部导航栏 -->
    <div class="upper-div">
      <button @click="DataShow">数据大厅</button>
      <button @click="Message">消息通知</button>
      <button @click="LoginedPage">用户登录</button>
    </div>

    <div class="two-div-container">
      <div class="left-div">
        <MapCharts class="map-charts" /> <!-- 导入MapCharts 组件 -->
      </div>
      <div class="right-div">
        <!-- 农业天气展示 -->
        <div class="right-up-div">
          <div v-if="weatherData && weatherData.now" class="weather-display">
            <h2>{{ weatherData.location.name }} - {{ weatherData.location.country }}</h2>
            <div class="weather-grid">
              <div class="weather-item">
                <span class="weather-label">天气状况：</span>
                <span class="weather-value">{{ weatherData.now.text }}</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">当前温度：</span>
                <span class="weather-value">{{ weatherData.now.temp }}°C</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">体感温度：</span>
                <span class="weather-value">{{ weatherData.now.feelsLike }}°C</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">风速：</span>
                <span class="weather-value">{{ weatherData.now.windSpeed }} km/h</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">风向：</span>
                <span class="weather-value">{{ weatherData.now.windDir }}</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">相对湿度：</span>
                <span class="weather-value">{{ weatherData.now.humidity }}%</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">降水量：</span>
                <span class="weather-value">{{ weatherData.now.precip }} mm</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">气压：</span>
                <span class="weather-value">{{ weatherData.now.pressure }} hPa</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">能见度：</span>
                <span class="weather-value">{{ weatherData.now.vis }} km</span>
              </div>
              <div class="weather-item">
                <span class="weather-label">云量：</span>
                <span class="weather-value">{{ weatherData.now.cloud }}%</span>
              </div>
            </div>
            <!-- 使用 v-if 指令控制图片显示 -->
            <img v-if="showWeatherIcon" :src="weatherIconUrl" alt="Weather icon" class="weather-icon" />
          </div>
          <div v-else>
            <p>加载中...</p>
          </div>
        </div>

        <!-- 危险消息通知区 -->
        <div class="message-container">
          <div
            v-for="msg in visibleMessages"
            :key="msg.id"
            class="message-item"
            :class="{'readed': msg.isRead}"
            @click="viewMessage(msg)"
          >
            <div class="message-content">
              <div class="message-title">{{ msg.title }}</div>
              <div class="message-preview">{{ msg.preview }}</div>
            </div>
            <button class="read-btn" @click.stop="readedMessage(msg.id)">已读</button>
          </div>

          <!-- 展开后的详细消息 -->
          <div v-if="selectedMessage" class="message-detail">
            <h3>{{ selectedMessage.title }}</h3>
            <p>{{ selectedMessage.content }}</p>
            <button @click="selectedMessage = null">关闭</button>
          </div>

          <!-- 加载更多按钮 -->
          <button v-if="showLoadMore" @click="loadMore" class="load-more-btn">
            加载更多
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import MapCharts from '@/components/MapChart.vue' 

const router = useRouter()

const DataShow = () => {
  router.push('/data')
}
const Message = () => {
  router.push('/message')
}
const LoginedPage = () => {
  router.push('/logined')
}

// 模拟消息数据
const allMessages = ref([
  { id: 1, title: '欢迎使用系统', preview: '这是一条预览内容', content: '这是一条完整的消息内容', isRead: false },
  { id: 2, title: '新通知', preview: '这里是新通知的预览', content: '完整的新通知内容', isRead: false },
  { id: 3, title: '提醒事项', preview: '提醒你明天要开会', content: '明天上午 9 点开会，请准时参加。', isRead: false },
  { id: 4, title: '系统更新', preview: '最新系统更新通知', content: '系统已更新至最新版本', isRead: false },
  { id: 5, title: '密码修改', preview: '请修改你的密码', content: '建议你修改密码以提高安全性', isRead: false },
  { id: 6, title: '会议安排', preview: '关于本周五的会议安排', content: '会议时间：2025年4月10日 上午9点', isRead: false },
  { id: 7, title: '员工活动', preview: '公司员工团建活动通知', content: '团建活动将在下周五举行', isRead: false },
  { id: 8, title: '系统维护', preview: '系统将于今晚进行维护', content: '预计维护时间为2小时', isRead: false },
  { id: 9, title: '支付通知', preview: '你的订单已支付成功', content: '订单号：123456789', isRead: false },
  { id: 10, title: '更新日志', preview: '最新版本的更新内容', content: '修复了已知Bug，提升了性能', isRead: false }
])

const visibleMessages = ref(allMessages.value.slice(0, 7))
const showLoadMore = ref(allMessages.value.length > visibleMessages.value.length)
const selectedMessage = ref(null)

const viewMessage = (msg) => {
  selectedMessage.value = msg
}

// 和风天气
const weatherData = ref(null)
const apiKey = '8bc680cde7d34a8e9751dd00a8edfb41'
const city = '101281301'  // 清远ID

const getWeather = async () => {
  try {
    const response = await axios.get(`https://devapi.qweather.com/v7/weather/now`, {
      params: {
        location: city,
        key: apiKey,
      },
    })

    console.log(response.data);

    if (response.data && response.data.now) {
      weatherData.value = {
        location: {
          name: '清远',
          country: '中国'
        },
        now: {
          text: response.data.now.text || '暂无天气信息',
          temp: response.data.now.temp || '未知温度',
          feelsLike: response.data.now.feelsLike || '未知',
          windSpeed: response.data.now.windSpeed || '未知风速',
          windDir: response.data.now.windDir || '未知风向',
          humidity: response.data.now.humidity || '未知湿度',
          precip: response.data.now.precip || '0',
          pressure: response.data.now.pressure || '未知气压',
          vis: response.data.now.vis || '未知能见度',
          cloud: response.data.now.cloud || '未知云量',
          icon: response.data.now.icon || '100'
        }
      }
    } else {
      console.error("返回的数据格式不正确", response.data);
      weatherData.value = {
        location: {
          name: '清远',
          country: '中国'
        },
        now: {
          text: '晴',
          temp: '25',
          feelsLike: '26',
          windSpeed: '10',
          windDir: '东南风',
          humidity: '65',
          precip: '0',
          pressure: '1012',
          vis: '10',
          cloud: '30',
          icon: '100'
        }
      }
    }
  } catch (error) {
    console.error('获取天气数据失败:', error);
    weatherData.value = {
      location: {
        name: '清远',
        country: '中国'
      },
      now: {
        text: '晴',
        temp: '25',
        feelsLike: '26',
        windSpeed: '10',
        windDir: '东南风',
        humidity: '65',
        precip: '0',
        pressure: '1012',
        vis: '10',
        cloud: '30',
        icon: '100'
      }
    }
  }
}

const weatherIconUrl = computed(() => {
  if (weatherData.value && weatherData.value.now) {
    return `https://cdn.heweather.com/cond_icon/${weatherData.value.now.icon}.png`
  }
  return ''
})

// 控制图片显示的变量
const showWeatherIcon = ref(false)

onMounted(() => {
  getWeather()
})

// 标记为已读
const readedMessage = (id) => {
  const msg = allMessages.value.find(m => m.id === id)
  if (msg) {
    msg.isRead = true
  }
  visibleMessages.value = visibleMessages.value.map(m => m.id === id ? { ...m, isRead: true } : m)
}

// 加载更多消息
const loadMore = () => {
  const currentLength = visibleMessages.value.length
  const nextMessages = allMessages.value.slice(currentLength, currentLength + 5)
  visibleMessages.value.push(...nextMessages)
  showLoadMore.value = allMessages.value.length > visibleMessages.value.length
}
</script>

<style scoped>
html, body {
  margin: 0;
  padding: 0;
  height: 100vh;
}

.upper-div {
  height: 50px;
  background-color: #f2f2f2;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 10px;
  box-sizing: border-box;
}

.upper-div button {
  margin-left: 20px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  cursor: pointer;
}

.two-div-container {
  display: flex;
  height: calc(100vh - 50px);
}

.left-div {
  flex: 1.5;
  border: 1px solid black;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.right-div {
  flex: 1;
  border: 1px solid black;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
}

.right-up-div {
  height: 220px; 
  border: 1px solid black;
  padding: 10px;
  box-sizing: border-box;
  overflow-y: auto; /* 添加滚动条以防内容过多 */
}

.weather-display {
  height: 100%;
  position: relative;
}

.weather-display h2 {
  margin: 0 0 10px 0;
  font-size: 16px;
  text-align: center;
}

.weather-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.weather-item {
  display: flex;
  align-items: center;
  padding: 4px 0;
}

.weather-label {
  font-weight: bold;
  margin-right: 5px;
  color: #333;
  font-size: 14px;
}

.weather-value {
  color: #666;
  font-size: 14px;
}

.weather-icon {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 50px;
  height: 50px;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  box-sizing: border-box;
}

.message-item {
  background: red; 
  border-radius: 10px;
  padding: 12px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background 0.3s;
}

.message-item.readed {
  background: green;
}

.message-content {
  cursor: pointer;
  flex-grow: 1;
}

.message-title {
  font-weight: bold;
  margin-bottom: 4px;
  color: white;
}

.message-preview {
  color: #eee;
  font-size: 14px;
}

.read-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-left: 10px;
}

.read-btn:hover {
  background: #096dd9;
}

.message-detail {
  margin-top: 20px;
  background: #fffbe6;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 0 6px rgba(0,0,0,0.1);
}

.load-more-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  width: 100%;
}

.load-more-btn:hover {
  background: #2563eb;
}

.map-charts {
  width: 100%; 
  height: 100%; 
}
</style>